package com.csnf.servlet;

import com.csnf.entity.User;
import com.csnf.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet({"/getUser","/editUser"})
public class UserServlet extends HttpServlet {
    UserService userService = new UserService();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getServletPath();
        switch(path) {
            case "/getUser":
                getUserByNickNames(req, resp);
                break;
            case "/editUser":
                getUserById(req, resp);
                break;
        }



    }
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        getUserName(req, resp);
    }


    private void getUserById(HttpServletRequest req, HttpServletResponse resp) {
        String user_id = req.getParameter("user_id");
        try {
            User user =  userService.getUserById(Integer.valueOf(user_id));
            req.setAttribute("user",user);
            req.getRequestDispatcher("editUser.jsp").forward(req, resp);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void getUserByNickNames(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String queryName= req.getParameter("queryName");//从请求获取查询条件

        try {
            List<User> usersList = userService.getAllByNickname(queryName);
            req.setAttribute("userList",usersList);
            req.getRequestDispatcher("success.jsp").forward(req, resp);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public void getUserName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer user_id = Integer.valueOf(req.getParameter("user_id"));
        String user_name = req.getParameter("user_name");
        String user_nickname = req.getParameter("user_nickname");
        try {
            boolean user = userService.getUserName(user_id,user_name,user_nickname);
            req.setAttribute("user",user);
            req.getRequestDispatcher("success.jsp").forward(req, resp);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
